class CartsController < ApplicationController
  
  # skip_before_filter :authorize, :only => [:create, :update, :destroy]
  before_filter :authorize_user, :only => [:index, :show ] #游客不能访问什么
  before_filter :authorize_admin, :only => [:index ] #普通用户不能访问什么
  
  before_action :set_cart, only: [:show, :edit, :update, :destroy]

  # GET /carts
  # GET /carts.json
  def index
    @carts = Cart.all
  end

  # GET /carts/1
  # GET /carts/1.json
  def show
    #购物车项目删除为空后
    @is_cart_show = true
    
    if current_cart = nil
      redirect_to user_url, :notice => '购物车已空'
    else
    
    begin
      # @cart = Cart.find(params[:id])
 
     @cart = Cart.find_by_user_id(session[:user_id])
    
        rescue ActiveRecord::RecordNotFound
          logger.error "尝试访问不存在的购物车 #{params[:id]}"
          redirect_to user_url, :notice => '购物车不存在'
        else
          respond_to do |format|
            format.html # show.html.erb
            format.xml { render :xml => @cart }
        end
      end
    end

  end

  # GET /carts/new
  def new
    @cart = Cart.new
  end

  # GET /carts/1/edit
  def edit
    @cart = current_cart
  end

  # POST /carts
  # POST /carts.json
  def create
    # @cart = Cart.new(cart_params)
    @cart = Cart.new(:product_id => product, :user_id => session[:user_id])
    p @cart
    p "创建购物车！！！！！！！！！！"
    respond_to do |format|
      if @cart.save
        format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
        format.json { render :show, status: :created, location: @cart }
      else
        format.html { render :new }
        format.json { render json: @cart.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /carts/1
  # PATCH/PUT /carts/1.json
  def update
    @cart = current_cart
    respond_to do |format|
      if @cart.update(cart_params)
        format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
        format.json { render :show, status: :ok, location: @cart }
      else
        format.html { render :edit }
        format.json { render json: @cart.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /carts/1
  # DELETE /carts/1.json
  def destroy
    @cart = current_cart
    @cart.destroy
    session[:cart_id] = nil
    # logger.warning "here"
    respond_to do |format|
      # format.html { redirect_to carts_url, notice: 'Cart was successfully destroyed.' }
      format.html { redirect_to store_url }
      format.js
      format.json { head :no_content }
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_cart
    # @cart = Cart.find(params[:id])
    
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def cart_params
    params[:cart]
  end
end
